<?php
class PostsController extends AppController {

	var $name = 'Posts';
	var $helpers = array('Html', 'Form');

	function add() {
		if (!empty($this->data)) {
		

		   if(!isset($this->data['Post']['city_id']) && !isset($this->data['Post']['profile_id']) && !isset($this->data['Post']['story_id']))
		   {
		   	$this->redirect(Controller::referer());
		   	exit;
		   }
		   
		   if(!isset($this->data['Post']['text']) || empty($this->data['Post']['text']))
		   {
		   	$this->Session->setFlash(__('Unable to save blank post.', true));
		   	$this->redirect(Controller::referer());
		   }
			
		   $user = $this->Auth->user();
		   $this->data['Post']['user_id'] = $user['User']['id'];
		   
			foreach($this->data['Post'] as $key => &$val)
			{
				$patterns = array( "/</", "/>/",);
			    $replacements = array( "&lt;", "&gt;");
				$val = preg_replace($patterns, $replacements, $val);
			}
		    
			if(strlen($this->data['Post']['text']) > 10000)
		     $this->data['Post']['text'] = substr($this->data['Post']['text'],0,10000) . '...truncated due to length.';
			
			$this->Post->create();
			if ($this->Post->save($this->data)) {
				$this->Session->setFlash(__('The post has been saved.', true));
				if(isset($this->data['Post']['city_id']))
				 $this->redirect(array('controller' => 'cities', 'action'=>'view', $this->data['Post']['city_id'] . '/#post_' . $this->Post->id));
				else if(isset($this->data['Post']['profile_id']))
				 $this->redirect(array('controller' => 'profiles', 'action'=> 'view', $this->data['Post']['profile_id'] . '/#post_' . $this->Post->id));
				else if(isset($this->data['Post']['story_id']))	
				 $this->redirect(array('controller' => 'stories', 'action' => 'view', $this->data['Post']['story_id'] . '/#post_' . $this->Post->id));
			} 
			
			
			
		}
		$this->Session->setFlash(__('Could not save post.', true));
		$this->redirect(array('controller' => 'profiles', 'action' => 'view'));
		
	}

	
	function delete($id = null) {
		
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for post.', true));
			$this->redirect(Controller::referer());
		}
		
		$user = $this->Auth->User();
		$user_id = $user['User']['id'];
		
		$post = $this->Post->findById($id);
		
		
		$user_profile = $this->Post->Profile->findByUserId($user_id);
		
		if(isset($post['Post']['id']))
		{
			if($user_id == $post['Story']['user_id'] || $user_id == $post['User']['id'] || ($user_profile['Profile']['id'] == $post['Profile']['id']))
			{
				if ($this->Post->del($id)) {
					$this->Session->setFlash(__('Post deleted.', true));
					$this->redirect(Controller::referer());
				}
			}
		}
		
		$this->Session->setFlash(__('Unable to delete post.', true));
		$this->redirect(Controller::referer());
		
	}
}
?>